import React, { PureComponent } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import Link from 'umi/link';
import * as Utils from '@/utils/utils';
import moment from 'moment';

import { Row, Col, Card, Table, Form, Button, Input, Select, Popconfirm, DatePicker, Tooltip } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AddBillForm from '@/components/AddBillForm';

import styles from './BillList.less';

const { Option } = Select;
const { Item: FormItem } = Form;

const { RangePicker, MonthPicker } = DatePicker;

const ModelName = 'mbl';

@connect(({ mbl, loading, tiDanState, port }) => ({
  loading: loading.models[ModelName],
  model: mbl,
  tiDanStates: tiDanState.list,

  sourcePorts: port.list.filter(r => r.portType === 1),
  targetPorts: port.list.filter(r => r.portType === 2),
}))
@Form.create()
class Comp extends PureComponent {
  state = {
    addFormVisible: false,
    current: {},
  };

  componentDidMount() {
    this.doQuery();
  }

  doQuery(cond) {
    const { dispatch, model } = this.props;
    let payload = {
      ...model.qc,
    };
    if (cond) {
      payload = {
        ...payload,
        ...cond,
      };
    }
    dispatch({
      type: `${ModelName}/getMBLView`,
      payload: payload,
    });
  }

  handlePageChange = (number, size) => {
    const cond = {
      pageSize: size,
      pageNumber: number,
    };
    this.doQuery(cond);
  };

  handleSearch = e => {
    e.preventDefault();

    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log('FIELDS VALUE', fieldsValue);

      let payload = {
        ...fieldsValue,
        year: fieldsValue.yearMonth ? fieldsValue.yearMonth.year() : 0,
        month: fieldsValue.yearMonth ? fieldsValue.yearMonth.month() + 1 : 0,
      };

      if (fieldsValue.isLock === 1) {
        // 如果要查询已核销的，才按核销日期查询.
        payload = {
          ...payload,
          lockDateStart:
            fieldsValue.lockDate &&
              Array.isArray(fieldsValue.lockDate) &&
              fieldsValue.lockDate.length === 2
              ? Utils.getChineseDate(fieldsValue.lockDate[0])
              : null,
          lockDateEnd:
            fieldsValue.lockDate &&
              Array.isArray(fieldsValue.lockDate) &&
              fieldsValue.lockDate.length === 2
              ? Utils.getChineseDate(fieldsValue.lockDate[1])
              : null,
        };
      }

      console.log('PAYLOAD', payload);
      delete payload.lockDate;
      delete payload.yearMonth;
      this.doQuery(payload);
    });
  };

  handleFormReset = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: `${ModelName}/reSetQC`,
    });
  };

  handleAddNewClicked = () => {
    this.setState({
      addFormVisible: true,
    });
  };

  handleDeleteClicked = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: `${ModelName}/deleteMBL`,
      payload: record.id,
      callback: resp => {
        if (resp) {
          // remove call back.
        }
      }
    });
  };

  handleAddBillFormSubmit = e => {
    const { dispatch } = this.props;
    const form = this.addBillForm.props.form;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const vm = {
        ...fieldsValue,
        objectNumber: fieldsValue.objectNumber.trim(),
      }

      dispatch({
        type: `${ModelName}/createOrUpdate`,
        payload: vm,
        callback: resp => {
          if (resp) {
            this.setState({ addFormVisible: false });
            router.push(`/Bill/${vm.objectNumber}/HBL`);
          }
        },
      });
    });
  };

  queryForm = () => {
    const {
      form: { getFieldDecorator },
      model,
      tiDanStates,
    } = this.props;

    const { qc } = model;

    const colSpanLayout = {
      xs: 24,
      md: 12,
      lg: 4,
    };

    const formLayout = {
      labelCol: {
        sm: { span: 7 },
      },
      wrapperCol: {
        sm: { span: 17 },
      },
    };

    return (
      <Form onSubmit={this.handleSearch}>
        <Row gutter={1} className={styles.dataRow}>
          <Col {...colSpanLayout}>
            <FormItem label="关键字" {...formLayout}>
              {getFieldDecorator('keyword', {
                initialValue: qc.keyword,
              })(<Input placeholder="单号、SO、销售员、港口..." />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="核销" {...formLayout}>
              {getFieldDecorator('isLock', {
                initialValue: qc.isLock,
              })(
                <Select placeholder="请选择">
                  <Option value={-1}>全部</Option>
                  <Option value={0}>未核销</Option>
                  <Option value={1}>已核销</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="提单状态" {...formLayout}>
              {getFieldDecorator('tiDanStateId', {
                initialValue: qc.tiDanStateId,
              })(
                <Select placeholder="请选择">
                  {tiDanStates.map(p => (
                    <Option value={p.id} key={p.id}>
                      {p.objectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={4}>
            <FormItem label="年月" {...formLayout}>
              {getFieldDecorator('yearMonth', {
                initialValue:
                  qc.year && qc.year > 0 && qc.month && qc.month > 0
                    ? moment(`${qc.year}-${qc.month}`)
                    : null,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col span={5}>
            <FormItem label="核销日期" {...formLayout}>
              {getFieldDecorator('lockDate', {
                initialValue:
                  qc.lockDateStart && qc.lockDateEnd
                    ? [moment(qc.lockDateStart), moment(qc.lockDateEnd)]
                    : null,
              })(<RangePicker />)}
            </FormItem>
          </Col>
          <Col span={3}>
            <div style={{ float: 'right' }}>
              <Button type="primary" htmlType="submit">
                查询
            </Button>
              <Button style={{ marginLeft: 4 }} onClick={this.handleFormReset}>
                重置
            </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const { model, loading } = this.props;
    const { addFormVisible } = this.state;
    const { data } = model;

    const testColumns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
    ];

    let columns = [
      {
        title: '#',
        dataIndex: 'ReNo',
        render: (text, record, index) => (
          <span> {index + 1 + (data.currentPage - 1) * data.pageSize} </span>
        ),
      },
      {
        title: '单号',
        dataIndex: 'objectNumber',
        render: (text, record) => <Tooltip title={record.id}><Link to={`/Bill/${text}/HBL`}>{text}</Link></Tooltip>,
      },
      {
        title: 'SO号',
        dataIndex: 'so',
      },
      {
        title: '业务员',
        dataIndex: 'salerName',
      },
      {
        title: '年月',
        dataIndex: 'year_Month',
        render: (text, record, index) => <span> {`${record.year}-${record.month}`}</span>,
      },
      {
        title: '提单状态',
        dataIndex: 'tiDanState',
      },
      {
        title: '核销',
        dataIndex: 'isLock',
        render: (text, record, index) => (
          <span> {record.isLock === 1 ? Utils.getChineseDate(record.lockDate) : '未核销'} </span>
        ),
      },
      {
        title: '起运港',
        dataIndex: 'sourcePort',
      },
      {
        title: '目的港',
        dataIndex: 'targetPort',
      },
      {
        title: '',
        key: 'action',
        render: (text, record) => (
          <Popconfirm title="确定要删除此项吗?" onConfirm={() => this.handleDeleteClicked(record)}>
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];

    if (process.env.NODE_ENV !== 'production') {
      columns = testColumns.concat(columns);
    }

    return (
      <PageHeaderWrapper>
        <Card
          title={<Button
            type="primary"
            // style={{ width: '100%', marginBottom: 8 }}
            // icon="plus"
            onClick={e => {
              e.preventDefault();
              this.handleAddNewClicked();
            }}
          >
            添加
          </Button>}
          bordered={false}>
          <div className={styles.tableListForm}>{this.queryForm()}</div>
          <Table
            key="id"
            rowKey="id"
            size="small"
            loading={loading}
            dataSource={data.dataList}
            columns={columns}
            pagination={{
              showSizeChanger: true,
              total: data.totalCount,
              pageSize: data.pageSize,
              current: data.currentPage,
              onChange: this.handlePageChange,
              onShowSizeChange: this.handlePageChange,
              showTotal: (total, range) => {
                return `共${total}项，当前显示 ${range[0]}-${range[1]}`;
              },
            }}
          />
        </Card>

        <AddBillForm
          visible={addFormVisible}
          onOk={this.handleAddBillFormSubmit}
          onCancel={() => this.setState({ addFormVisible: false })}
          getInstance={form => (this.addBillForm = form)}
        />
      </PageHeaderWrapper>
    );
  }
}



export default Comp;
